
#include "../src/thread.h"
#include"fifi.h"

int cmpt = 1;

static int FIBO_SIZE;

double getTime(){
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return 1000*tv.tv_sec+tv.tv_usec/1000.0;
}

int fibo (int n){

  if(n == 0){
    thread_exit(n);
    return 0;
}
  else if(n  ==1){
    thread_exit(n);
	return 1;
}
  else{
    void* retval1; 
    void* retval2;
    int err;
    int a = n - 1;
    int b = n - 2;

    thread_t t1,t2;
    err=thread_create(&t1, (void * (*) (void*)) fibo, (void*)a); 
		assert(!err);
    err=thread_create(&t2, (void * (*) (void*)) fibo,(void*)b);
		assert(!err);
    
    cmpt+=2;
    err=thread_join(t1, &retval1);
		assert(!err);
    err=thread_join(t2, &retval2);
		assert(!err);
/*
    if(b == FIBO_SIZE - 2)
      printf("FIBO[%d] = %g\n",b,fibtab[b]);
    if(a == FIBO_SIZE - 1)
      printf("FIBO[%d] = %g\n",a,fibtab[a]);    
    
    fibtab[*(int*)n] = fibtab[a] + fibtab[b];*/
    int temp1 = (int)retval1;
    int temp2 = (int)retval2;
    int temp3 = temp1+temp2;
    thread_exit(temp3);
	return temp3;
  }
}

float* affichage(int n){

  printf("\n.......Calcul de FIBO(%d) ..... \n",n); 

  /* On initialise le tableau */
  int i;
  int err; 
  /* On calcule fibo(n) */
  void *resultat;
  double t1 = getTime();
  thread_t thread1;
  err=thread_create(&thread1,(void * (*) (void*))fibo,(void *)n);
	assert(!err);
  err=thread_join(thread1 , &resultat);
	assert(!err);
  double t2 = getTime();

  /* On affiche le résultat */
  printf(".......Resultat FIBO");
  printf("[%d] = %d\n",n,(int )resultat);
  printf("   [Cout de calcul = %g ms]\n", t2 - t1);
  printf(" [Nombre de threads utilisés : %d]\n",cmpt);
  float result[2]={t2-t1, (float)cmpt};
  return result; 
}


int main (int argc,char **argv){
	if(argc==1){
		printf("veuillez donner un entier en parametre\n");
		return EXIT_FAILURE;
	}
 	FIBO_SIZE=atoi(argv[1]); 
 	affichage(FIBO_SIZE);
 	return EXIT_SUCCESS;
 }
